package com.maple.utils.widget.receiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.blankj.utilcode.util.TimeUtils
import java.text.SimpleDateFormat

class ClockReceiver(val context: Context,val listener: OnTickListener?): BroadcastReceiver(), DefaultLifecycleObserver {

    private val dateFormat: SimpleDateFormat by lazy {
        TimeUtils.getSafeDateFormat("yyyy-MM-dd HH:mm")
    }

    init {
        val time = TimeUtils.getNowString(dateFormat)
        listener?.tick(time)
    }

    override fun onReceive(context: Context?, intent: Intent?) {
        if(listener == null) return
        intent?.let {
            when (it.action) {
                Intent.ACTION_TIME_TICK -> {
                    val time = TimeUtils.getNowString(dateFormat)
                    listener.tick(time)
                }
                else -> {}
            }
        }
    }


    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        val filter = IntentFilter()
        filter.addAction(Intent.ACTION_TIME_TICK);
        context.registerReceiver(this,filter)
    }

    override fun onDestroy(owner: LifecycleOwner) {
        super.onDestroy(owner)
        context.unregisterReceiver(this)
    }

    interface OnTickListener{
        fun tick(time: String)
    }
}